<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportData">导出</el-button>
          <el-button size="small" type="primary" :disabled="!checkPermission('aa')" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card v-loading="loading">
        <el-table :data="list" border>
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column align="center" width="150px" label="头像" prop="staffPhoto" sortable="">
            <template slot-scope=" {row}">
              <img
                v-imageerror="require('@/assets/head.jpg')"
                :src="row.staffPhoto"
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                alt=""
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatter" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template slot-scope="scope">
              {{ scope.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="enableState" sortable="">
            <template slot-scope="scope">
              <el-switch :value="scope.row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination :current-page="page.page" :total="page.total" :page-size="page.size" layout="prev, pager, next" @current-change="pageChange" />
        </el-row>
      </el-card>
      <AddDemployee :show-dialog.sync="showDialog" />
      <el-dialog title="二维码" :visible.sync="showCodeDialog" @close="imgUrl=''">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <assignRole v-if="showRoleDialog" ref="assignRole1" :show-role-dialog.sync="showRoleDialog" />
    </div>
  </div>
</template>

<script>
import AddDemployee from './components/add-employee.vue'
import EmployeeEnum from '@/api/constant/employees'
import { getEmployeeList, delEmployee } from '@/api/employees'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'
import assignRole from '@/views/employees/components/assign-role.vue'
export default {
  components: {
    AddDemployee, assignRole
  },
  data() {
    return {
      showDialog: false,
      list: [],
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      loading: false,
      showCodeDialog: false,
      showRoleDialog: false
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.list = rows
      this.page.total = total
      this.loading = false
    },
    pageChange(newPage) {
      this.page.page = newPage
      this.getEmployeeList(this.page)
    },
    formatter(cellValue) {
      const obj = EmployeeEnum.hireType.find(item => item.id === +cellValue.formOfEmployment)
      return obj ? obj.value : '未知状态'
    },
    async delEmployee(id) {
      try {
        await this.$confirm('确定要删除该员工吗')
        await delEmployee(id)
        this.getEmployeeList(this.page)
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      } catch (error) {
        console.log(error)
      }
    },
    async exportData() {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
      const data = this.formatJson(headers, rows)
      import('@/vendor/Export2Excel').then(execl => {
        execl.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '员工信息表'
        })
      })
    },
    formatJson(headers, rows) {
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(itemEnum => itemEnum.id === +item[headers[key]])
            return obj ? obj.value : '未知'
          }
          return item[headers[key]]
        })
      })
    },
    showQrCode(url) {
      if (url) {
        this.showCodeDialog = true
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, url)
        })

        // console.log(this.$refs.myCanvas)
      } else {
        this.$message.warning('用户还未上传头像')
      }
    },
    editRole(id) {
      // console.log(this.$refs)
      this.showRoleDialog = true
      setTimeout(async() => {
        // console.log(this)
        await this.$refs.assignRole1.getUserInfoByID(id)
      }, 0)
    }
  }
}
</script>

<style>

</style>
